package com.koomii.myproject.service.impl;


import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import com.koomii.common.redis.RedisCache;
import com.koomii.myproject.dao.LocationDao;
import com.koomii.myproject.domain.entity.Location;
import com.koomii.myproject.service.LocationService;

/**
 *
 * LocationServiceImpl
 *
 * @author 
 *
 */
@Service("locationService")
public class LocationServiceImpl  implements LocationService{
	private final String CACHE_KEY_LOCATION = "Location_";
	private final String CACHE_KEY_LOCATION_LIST = "LocationList";
	
	@Autowired
	private LocationDao locationDao;
	
	@Autowired
	private RedisCache redisCache;
	
	@Override
	public Long save(Location location){
		redisCache.set(CACHE_KEY_LOCATION+location.getId(), location, 1, TimeUnit.MINUTES);
		return locationDao.save(location);
	}

	@Override
	public void update(Location location){
		redisCache.set(CACHE_KEY_LOCATION+location.getId(), location, 1, TimeUnit.MINUTES);
		locationDao.update(location);
	}

	@Override
	public void delete(Long id){
		redisCache.delete(CACHE_KEY_LOCATION+id);
		locationDao.delete(id);
	}

	@Override
	public Location findById(Integer id){
		Location location = redisCache.get(CACHE_KEY_LOCATION+id,Location.class);
		if(location == null){
			location = locationDao.findById(id);
			redisCache.set(CACHE_KEY_LOCATION+location.getId(), location, 1, TimeUnit.MINUTES);
		}
		return location;
	}

	@Override
	public List<String> findProvinceList() {
		List<String> provinceList = redisCache.getList(CACHE_KEY_LOCATION_LIST,String.class);
		if(provinceList == null){
			provinceList = locationDao.findProvinceList();
			redisCache.set(CACHE_KEY_LOCATION_LIST, provinceList, 1, TimeUnit.MINUTES);
		}
		return provinceList;
	}

	@Override
	public List<String> findCityList(String province) {
		List<String> cityList = redisCache.getList(CACHE_KEY_LOCATION_LIST+"_"+province,String.class);
		if(cityList == null){
			cityList = locationDao.findCityList(province);
			redisCache.set(CACHE_KEY_LOCATION_LIST+"_"+province, cityList, 1, TimeUnit.MINUTES);
		}
		return cityList;
	}

	@Override
	public List<Location> findLocationList(String province, String city) {
		return locationDao.findLocationList(province,city);
	}
}